const express = require('express');
const app = express();
const server = app.listen(3000);

const webSocket = require('socket.io');
const io = webSocket(server);

// socket对象
// console.log(io);

app.use(express.static('./dist'))

const messageArr = { all: [] };

let RoomSocket = {};

io.on('connect', (socket) => {
    const room = socket.handshake.query.room;
    if (room) {
        socket.join(room, () => { })
        // socket套接字信息
        socket.on('receiveData', data => {
            if (!messageArr[room]) messageArr[room] = [];
            messageArr[room].push(data);
            RoomSocket[room] = true;
            // 同房间实时获取，socket.to(房间号)其实就是获取对应房间号的其他所有socket集合
            socket.to(room).emit('sendMessage', messageArr[room]);
            // 自己实时获取
            socket.emit('sendMessage', messageArr[room]);
        });
        // 加入房间获取历史消息
        socket.emit('sendMessage', messageArr[room]);
    } else {
        // socket套接字信息
        socket.on('receiveData', data => {
            messageArr.all.push(data);
            io.sockets.emit('sendMessageAll', messageArr.all);
        })
    }
})